const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");

router.post('/home/bottom', async ctx => {
    try {
        let tenantId = ctx.user.tenantId;
        let body = ctx.request.body;
        let billType = body.billType
        let range = body.range
        let tabType = body.tabType
        let ph = tool.xe.toNumber(body.ph)
        if( range) {
            let beginDate = ''
            let endDate = ''
            if(range === '近一周'){
                endDate = tool.getDay('')
                beginDate = tool.getDay('', -7)
            }
            if(range === '近30天'){
                endDate = tool.getDay('')
                beginDate = tool.getDay(tool.dayjs().subtract(30, 'day'))
            }
            if(range === '近半年'){
                endDate = tool.getDay('',  )
                beginDate = tool.getDay(tool.dayjs().subtract(6, 'month'))
            }
            if(range === '近一年'){
                endDate = tool.getDay('',  )
                beginDate = tool.getDay(tool.dayjs().subtract(1, 'year'))
            }
            if(range === '全部'){
                endDate = '2000-01-01'
                beginDate = tool.getDay()
            }
            if (tabType==='终端贡献') {
                let sqls = `select sum(totalAmount) total from v_main where tenantId=${tenantId} and billState='accounted' and transType=150601 
and billDate between '${beginDate}' and '${endDate}' `
                let total = await db.query(sqls, {type: QueryTypes.SELECT, plain: true})
                let totalAmount = 0
                if(total) totalAmount = tool.xe.toNumber(total.total)
                ph = ph ? ph : 5

                let phsql = `select top ${ph} a.buId,b.name buName,b.linkName,b.address,a.totalAmount from (
                                           select tenantId,buId, sum(totalAmount) totalAmount from v_main where tenantId=${tenantId} and billState='accounted' and transType=150601
                                                                                             and billDate between '${beginDate}' and '${endDate}' group by tenantId, buId
                                       ) a inner join contact b on a.tenantId=b.tenantId and a.buId=b.id order by a.totalAmount desc  `
                let phlist = await db.query(phsql, {type: QueryTypes.SELECT})
                let khamount = 0
                for (let i = 0; i < phlist.length; i++) {
                    khamount = tool.xe.add(khamount, phlist[i].totalAmount)
                    let sub = tool.xe.toNumber(phlist[i].totalAmount)
                    phlist[i].totalAmount = tool.xe.toFixed(phlist[i].totalAmount, 2)
                    phlist[i].ratio = totalAmount!==0?(tools.xe.toFixed(tools.divide(sub, totalAmount)*100,2)):''
                }
                let zezb = totalAmount!==0?(tools.xe.toFixed(tools.divide(khamount, totalAmount)*100,2)+'%'):''
                let ret = {
                    tj: [
                        {text: '终端销售', total: '￥'+tools.xe.toFixed(khamount,2)},
                        {text: '所有终端销售', total: '￥'+tools.xe.toFixed(totalAmount,2)},
                        {text: '总额占比', total: zezb},
                    ],
                    list: phlist
                }
                return ctx.suc('', ret)
            }
            if (tabType === '单品贡献') {
                let sqls = `
                    select sum(isnull(b.amount,0)) total from
                        invoice a inner join v_main_info b on a.tenantId=b.tenantId and a.id=b.iid
                    where a.tenantId=${tenantId} and a.billState='accounted' and a.transType=150601
                      and billDate between '${beginDate}' and '${endDate}' 
                `
                let total = await db.query(sqls, {type: QueryTypes.SELECT, plain: true})
                let totalAmount = 0
                if(total) totalAmount = tool.xe.toNumber(total.total)
                ph = ph ? ph : 5

                let phsql = `select top ${ph} a.invId,b.name invName,b.unit1,b.spec,a.totalAmount from (
                                           select a.tenantId,b.invId, sum(isnull(b.amount,0)) totalAmount from 
                                           invoice a inner join v_main_info  b on a.tenantId=b.tenantId and a.id=b.iid 
                                           where a.tenantId=${tenantId} and a.billState='accounted' and a.transType=150601
                                           and billDate between '${beginDate}' and '${endDate}' group by a.tenantId, b.invId
                                       ) a inner join v_goods b on a.tenantId=b.tenantId and a.invId=b.id order by a.totalAmount desc  `
                let phlist = await db.query(phsql, {type: QueryTypes.SELECT})
                let khamount = 0
                for (let i = 0; i < phlist.length; i++) {
                    phlist[i].spec = '1*' + phlist[i].spec
                    khamount = tool.xe.add(khamount, phlist[i].totalAmount)
                    let sub = tool.xe.toNumber(phlist[i].totalAmount)
                    phlist[i].totalAmount = tool.xe.toFixed(phlist[i].totalAmount, 2)
                    phlist[i].ratio = totalAmount!==0?(tools.xe.toFixed(tools.divide(sub, totalAmount)*100,2)):''
                }
                let zezb = totalAmount!==0?(tools.xe.toFixed(tools.divide(khamount, totalAmount)*100,2)+'%'):''
                let ret = {
                    tj: [
                        {text: '商品销售额', total: '￥'+tools.xe.toFixed(khamount,2)},
                        {text: '所有商品销售额', total: '￥'+tools.xe.toFixed(totalAmount,2)},
                        {text: '总额占比', total: zezb},
                    ],
                    list: phlist
                }
                return ctx.suc('', ret)
            }
            if (tabType==='终端分类贡献') {
                let sqls = `select sum(totalAmount) total from v_main where tenantId=${tenantId} and billState='accounted' and transType=150601 
and billDate between '${beginDate}' and '${endDate}' and contactCatName<>'' `
                let total = await db.query(sqls, {type: QueryTypes.SELECT, plain: true})
                let totalAmount = 0
                if(total) totalAmount = tool.xe.toNumber(total.total)

                let phsql = `select contactCatName catName, a.totalAmount from (
                                           select contactCatName, sum(totalAmount) totalAmount from v_main where 
                                           tenantId=${tenantId} and billState='accounted' and transType=150601
                                           and billDate between '${beginDate}' and '${endDate}' and contactCatName<>'' group by contactCatName
                                       ) a  order by a.totalAmount desc  `
                let phlist = await db.query(phsql, {type: QueryTypes.SELECT})
                let khamount = 0
                for (let i = 0; i < phlist.length; i++) {
                    khamount = tool.xe.add(khamount, phlist[i].totalAmount)
                    let sub = tool.xe.toNumber(phlist[i].totalAmount)
                    phlist[i].totalAmount = tool.xe.toFixed(phlist[i].totalAmount, 2)
                    phlist[i].ratio = totalAmount!==0?(tools.xe.toFixed(tools.divide(sub, totalAmount)*100,2)):''
                }
                let zezb = totalAmount!==0?(tools.xe.toFixed(tools.divide(khamount, totalAmount)*100,2)+'%'):''
                let ret = {
                    tj: [],
                    list: phlist
                }
                return ctx.suc('', ret)
            }
            if (tabType === '商品分类贡献') {
                let sqls = `
                    select sum(isnull(b.amount,0)) total from
                        invoice a inner join v_main_info b on a.tenantId=b.tenantId and a.id=b.iid
                    where a.tenantId=${tenantId} and a.billState='accounted' and a.transType=150601
                      and billDate between '${beginDate}' and '${endDate}' and b.goodCatName<>'' 
                `
                let total = await db.query(sqls, {type: QueryTypes.SELECT, plain: true})
                let totalAmount = 0
                if(total) totalAmount = tool.xe.toNumber(total.total)

                let phsql = `select goodCatName catName,a.totalAmount from (
                                           select b.goodCatName, sum(isnull(b.amount,0)) totalAmount from 
                                           invoice a inner join v_main_info b on a.tenantId=b.tenantId and a.id=b.iid 
                                           where a.tenantId=${tenantId} and a.billState='accounted' and a.transType=150601
                                           and billDate between '${beginDate}' and '${endDate}' and b.goodCatName<>'' group by  goodCatName
                                       ) a  order by a.totalAmount desc  `
                let phlist = await db.query(phsql, {type: QueryTypes.SELECT})
                let khamount = 0
                for (let i = 0; i < phlist.length; i++) {
                    phlist[i].spec = '1*' + phlist[i].spec
                    khamount = tool.xe.add(khamount, phlist[i].totalAmount)
                    let sub = tool.xe.toNumber(phlist[i].totalAmount)
                    phlist[i].totalAmount = tool.xe.toFixed(phlist[i].totalAmount, 2)
                    phlist[i].ratio = totalAmount!==0?(tools.xe.toFixed(tools.divide(sub, totalAmount)*100,2)):''
                }
                let zezb = totalAmount!==0?(tools.xe.toFixed(tools.divide(khamount, totalAmount)*100,2)+'%'):''
                let ret = {
                    tj: [
                        {text: '商品销售额', total: '￥'+tools.xe.toFixed(khamount,2)},
                        {text: '所有商品销售额', total: '￥'+tools.xe.toFixed(totalAmount,2)},
                        {text: '总额占比', total: zezb},
                    ],
                    list: phlist
                }
                return ctx.suc('', ret)
            }
            let ret = {
                tj: [],
                list: []
            }
            return ctx.suc('', ret)
        }
        else {
            return ctx.err('没有选择条件')
        }

    } catch (e) {
        return ctx.err(e);
    }
})


module.exports = router;
